package com.hn658.base.message.managermq.init;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.jms.ConnectionFactory;
import javax.jms.Destination;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import com.hn658.base.message.appinfo.entity.AppMqConfigEO;
import com.hn658.base.message.managermq.JmsTemplateManager;
import com.hn658.base.message.managermq.config.provider.MqConfigProvider;
import com.hn658.base.message.managermq.contants.MQManagerContants;
import com.hn658.base.message.managermq.template.MqTemplate;

/**
 * 
 * ActiveMq队列初始化
 * @author ztjie
 * @date 2015-11-19 下午3:52:01
 * @since
 * @version
 */
@Component
public class ActiveMqJmsTemplateInit implements InitializingBean {
	
	@Autowired
	private MqConfigProvider mqConfigProvider;
	
	@Autowired
	private ConnectionFactory jmsConnectionFactory;
	
	@Autowired
	private ActiveMqDestinationInit activeMqDestinationInit;
	
	private Lock lock = new ReentrantLock();

	@Autowired
	private JmsTemplateManager jmsTemplateManager;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		lock.lock();
		try{
			List<AppMqConfigEO> configList = mqConfigProvider.queryConfig();
			for(AppMqConfigEO config : configList){
				MqTemplate temp = new MqTemplate();
				String key=config.getAppId()+"_"+config.getQueuePriority();
				temp.setName(MQManagerContants.TEMPLATE+"_"+key);
				temp.setConnectionFactoryName(MQManagerContants.CONNECTIONFACTORY);
				temp.setDefaultDestinationName(MQManagerContants.DESTINATION+"_"+key);
				String pubSubDomainName=config.getQueueType()==1?"false":"true";
				temp.setPubSubDomainName(pubSubDomainName);
				jmsTemplateManager.add(config.getAppId(), config.getQueuePriority(), temp);
			}		
		}finally{
			lock.unlock();			
		}
	}
}
